﻿// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file, You can obtain one at https://opensource.org/licenses/MIT.
// Copyright (C) Leszek Pomianowski and WPF UI Contributors.
// All Rights Reserved.

using System.Globalization;
using System.Net.Http;
using Microsoft.Web.WebView2.Wpf;

namespace BluePig.Wpf.ViewModels;

public partial class LearningPageViewModel : ObservableObject
{
    [ObservableProperty] private int _learnedCount;
    [ObservableProperty]
    private string? _en;

    [ObservableProperty] 
    private string _cn = "你好";

    private Word _word;

    [ObservableProperty]
    private string _url = "https://33.agilestudio.cn/?subtitleKeyword=word&exactFlag=0&phraseMode=0&page=1&limit=20";

    private readonly List<Word> _words;
    private List<Word> _unWatchWords;

    private readonly swaggerClient _client;
    public LearningPageViewModel()
    {
        _client = new swaggerClient("http://localhost:18104/", new HttpClient());
        _words = _client.WordsAllAsync().Result.ToList();
        _unWatchWords = _words.Where(r => r.IsWatched == false).ToList();
        _word = _unWatchWords.First();
        En = _word.En;
        Cn = _word.Cn;
        Url = $@"https://33.agilestudio.cn/?subtitleKeyword={En}&exactFlag=0&phraseMode=0&page=1&limit=20";
        InitTodayTarget();
    }

    [RelayCommand]
    private async Task NextWord(WebView2 r)
    {
        await TraceNotEasy();
        await WatchedWord();
        Next();
    }

    [RelayCommand]
    private async Task SoEasy()
    {
        await TraceEasy();
        await TooEasy();
        await WatchedWord();
        Next();
    }
    private void InitTodayTarget()
    {
        LearnedCount = _client.WordsAllAsync().Result.ToList().Count(r => DateTime.Parse(r.LastUpdateDate).Day == DateTime.Now.Day);
    }
    private void Next()
    {
        var random = new Random();
        _word = _unWatchWords[random.Next(0, _unWatchWords.Count)];
        En = _word.En;
        Cn = _word.Cn;
        Url = $@"https://33.agilestudio.cn/?subtitleKeyword={En}&exactFlag=0&phraseMode=0&page=1&limit=20";
        InitTodayTarget();
    }

    private async Task WatchedWord()
    {
        _word.IsWatched = true;
        _word.LastUpdateDate = DateTime.Now.ToString(CultureInfo.CurrentCulture);
        await _client.Words3Async(_word.Id, _word);
    }

    private async Task TooEasy()
    {
        _word.IKnewIt = true;
        await _client.Words3Async(_word.Id, _word);
        _unWatchWords = _client.WordsAllAsync().Result.Where(r => r.IsWatched == false).ToList();
    }

    private async Task TraceEasy()
    {
        await _client.TracesAsync(new Trace() { En = _en,SoEasy = true});
    }

    private async Task TraceNotEasy()
    {
        await _client.TracesAsync(new Trace() { En = _en,SoEasy = false});
    }
}
